package com.sloera.net;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class BIOClient {
    /*
     * @Description 调用远程服务
     * @param host: 主机ip
     * @param port: 商品
     * @param reqObj: 请求对象
     * @Return java.lang.Object 响应结果
     * @Author SloeraN
     * @Date 2020/3/19 0:00
     */
    public static Object callRemoteProcedure(String host, int port, Object reqObj) {

        ObjectInputStream ois = null;
        ObjectOutputStream oos = null;
        Object respObject = null;

        try {
            Socket socket = new Socket(host, port);
            oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject(reqObj);
            oos.flush();

            ois = new ObjectInputStream(socket.getInputStream());
            respObject = ois.readObject(); // 读取输入对象

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return respObject;
    }
}
